<?php

namespace App\Http\Controllers\Admin\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\AdminResource;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\AdminHasRole;
use App\Traits\ApiResponse;
use Tymon\JWTAuth\Facades\JWTAuth;
use Auth;

class AdminController extends Controller
{

    use ApiResponse;

    public function __construct()
    {
    }

    /**
     * 管理员登录
     * @Author wuyan（466720682@qq.com）
     * @return [Array]
     */
    public function login(Request $request)
    {
        info($request->all());
        $data = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string|min:5'
        ]);
        $admin = Admin::where(['username' => $data['username']])->first();
        if ( empty($admin) ) {
            if ( $data['username'] !== 'admin' ) {
                return $this->responseFailed('用户不存在');
            } else {
                Admin::createFirst();
            }
        }
        $token = auth('admin')->attempt($data);
        if ( $token ) {
            return $this->responseSucceed([
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => JWTAuth::factory()->getTTL() * 60,
            ]);
        }
        return $this->responseUnauthorized();
    }

    /**
     * 退出登录
     * @return \Illuminate\Http\JsonResponse
     */
    public function outLogin()
    {
        auth('admin')->logout();
        return $this->responseSucceed();
    }

    /**
     * 当前登录用户
     * @Author wuyan（466720682@qq.com）
     * @return [Array]
     */
    public function me()
    {
        $userInfo = Auth::user();
        return $this->responseSucceed(new AdminResource($userInfo));
    }

    /**
     * 管理员列表
     * @Author wuyan（466720682@qq.com）
     * @return [Array]
     */
    public function lists()
    {
        $admin = Admin::query()->paginate(10);
        foreach ( $admin as &$val ) {
            // 获取当前用户的所有角色
            $has_role = AdminHasRole::query()->where('admin_id', $val['id'])->pluck('role_id')->toArray();
            $val['roles'] = $has_role;
        }
        return $this->responseSucceed([
            'data' => $admin->items(),
            'total' => $admin->total(),
            'success' => true
        ]);
    }

    /**
     * 管理员创建
     * @Author wuyan（466720682@qq.com）
     * @return [Boolean]
     */
    public function create(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'username' => 'required|string',
            'password' => 'required|string|min:6',
            'roles' => 'array'
        ]);
        $data['password'] = bcrypt($data['password']);
        (new Admin())->createAdmin($data);
        return $this->responseCreated();
    }

    /**
     * 管理员更新
     * @Author wuyan（466720682@qq.com）
     * @return [Boolean]
     */
    public function update($id, Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'username' => 'required|string',
            'password' => 'string|min:6',
            'roles' => 'array'
        ]);
        if ( isset($data['password']) )
            $data['password'] = bcrypt($data['password']);
        (new Admin())->updateAdmin($id, $data);
        return $this->responseSucceed();
    }

    /**
     * 管理员删除
     * @Author wuyan（466720682@qq.com）
     * @return [Boolean]
     */
    public function delete($id)
    {
        AdminHasRole::query()->where('admin_id', $id)->delete();
        Admin::query()->where('id', $id)->delete();
        return $this->responseSucceed();
    }

}
